'use client';
import { useAuthStore } from '@/store/useAuthStore';
import { message } from 'antd';
import dd from 'dingtalk-jsapi';
import { useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useSWRConfig } from 'swr';

export const useAuth = () => {
	const getToken = useAuthStore(s => s.getToken);
	const setToken = useAuthStore(s => s.setToken);
	const token = useAuthStore(s => s.token);
	const router = useRouter();
	const { mutate } = useSWRConfig();
	useEffect(() => {
		if (typeof window === 'undefined') {
			return;
		}
		const urlObj = new URL(window.location.href);
		const urlToken = urlObj.searchParams.get('access_token');
		if (urlToken) {
			urlObj.searchParams.delete('access_token');
			router.replace(
				window.location.pathname + '?' + urlObj.searchParams.toString()
			);
			setToken(urlToken);
			return;
		}
		if (token) return;
		const localToken = getToken();
		if (!localToken) {
			message.error('请先登录');
			// window.location.href = process.env.NEXT_PUBLIC_APP_ENV === 'development' ? '/cg06/login' : '/cg06/login.html'
		}
	}, [token]);
	return token;
};

